import 'package:flutter/material.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:scan_barcode/scan_barcode.dart';
import 'package:shirne_dialog/shirne_dialog.dart';
import '../home/scan.dart';
import '../../models/siteinfo_model.dart';
import '../../application.dart';
import '../../widgets/card_widget.dart';
import '../../models/article_model.dart';
import '../../models/list_result.dart';
import '../../models/product_model.dart';
import '../../utils/api.dart';
import '../../utils/tools.dart';
import '../../widgets/article_widget.dart';
import '../../widgets/product_widget.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin<HomePage> {
  final String _title = "临风小筑";
  List<dynamic>? _banners;
  List<dynamic>? _cates;
  ListResult<ArticleModel>? _articles;
  ListResult<ProductModel>? _products;

  bool _loaded = false;
  final bool _isError = false;

  SiteinfoModel? siteinfo;

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
      body: SafeArea(
        child: _loaded
            ? RefreshIndicator(
                onRefresh: () {
                  return _loadData();
                },
                child: CustomScrollView(
                  physics: const AlwaysScrollableScrollPhysics()
                    ..applyTo(const BouncingScrollPhysics()),
                  slivers: [
                    SliverAppBar(
                      pinned: true,
                      expandedHeight: MediaQuery.of(context).size.width * 0.6,
                      backgroundColor: Colors.transparent,
                      elevation: 1,
                      title: Text(_title),
                      actions: [
                        IconButton(
                          onPressed: () async {
                            var result =
                                await Navigator.of(context).push<Barcode?>(
                              MaterialPageRoute<Barcode?>(
                                builder: (context) {
                                  return const ScanPage();
                                },
                              ),
                            );
                            if (result != null) {
                              MyDialog.alert(result.rawValue ?? '未识别到内容');
                            }
                          },
                          icon: const Icon(Icons.center_focus_weak),
                        ),
                      ],
                      flexibleSpace: FlexibleSpaceBar(
                        background: _renderBanner(),
                        //titlePadding: EdgeInsets.only(right: 50.0),
                        //centerTitle: true,
                        collapseMode: CollapseMode.parallax,
                      ),
                    ),
                    const SliverPadding(padding: EdgeInsets.only(top: 10)),
                    if (_cates != null && _cates!.isNotEmpty)
                      SliverToBoxAdapter(
                        child: _CategoryWidget(_cates!),
                      ),
                    if (_products != null && _products!.hasList)
                      SliverGrid.count(
                        crossAxisCount: 2,
                        children: _products!.lists!
                            .map(
                              (item) => Padding(
                                padding: const EdgeInsets.only(
                                  left: 10,
                                  right: 10,
                                  bottom: 10,
                                ),
                                child: ProductWidget(item),
                              ),
                            )
                            .toList(),
                      ),
                    if (_articles != null && _articles!.hasList)
                      SliverList(
                        delegate: SliverChildListDelegate(
                          _articles!.lists!
                              .map(
                                (item) => Padding(
                                  padding: const EdgeInsets.only(
                                    left: 10,
                                    right: 10,
                                    bottom: 10,
                                  ),
                                  child: ArticleWidget(
                                    item,
                                    cols: 2,
                                    heroTag: 'index_article_${item.id}',
                                  ),
                                ),
                              )
                              .toList(),
                        ),
                      ),
                    SliverToBoxAdapter(
                      child: Padding(
                        padding: const EdgeInsets.only(bottom: 30),
                        child: Center(
                          heightFactor: 2,
                          child: Text(
                            siteinfo != null ? siteinfo!.webname : ' - ',
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              )
            : const Center(child: CircularProgressIndicator()),
      ),
    );
  }

  Widget _renderBanner() {
    return (_banners?.isEmpty ?? true)
        ? Container(
            color: Theme.of(context).colorScheme.surface,
          )
        : _BannerWidget(_banners!);
  }

  Future<void> _loadData() async {
    app.getSiteinfo().then((result) {
      if (!mounted) return;
      setState(() {
        siteinfo = result;
      });
    });
    final result = await Api.post('common/batch', {
      'product.get_list': {'withsku': 1, 'type': 4, 'pagesize': 4},
      'product.get_cates': {'goods_count': 4, 'withsku': 1},
      'article.get_list': {},
      'advs': {'flag': 'banner'},
    });
    var data = result.data;
    if (data == null) return;
    if (!mounted) return;
    setState(() {
      _banners = data['advs'];
      _cates = data['product.get_cates'];
      _products = ListResult<ProductModel>.fromJson(
        data['product.get_list'],
        (Map? item) => ProductModel.fromJson(item),
      );
      _articles = ListResult<ArticleModel>.fromJson(
        data['article.get_list'],
        (Map? item) => ArticleModel.fromJson(item),
      );

      _loaded = true;
    });
  }

  @override
  bool get wantKeepAlive => true;
}

class _BannerWidget extends StatelessWidget {
  final List _banners;

  const _BannerWidget(this._banners, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final bannerWidth = size.width;
    final bannerHeight = size.width * .6;

    return Swiper(
      itemWidth: bannerWidth,
      itemHeight: bannerHeight,
      viewportFraction: 0.9,
      scale: 0.95,
      itemBuilder: (context, idx) {
        final item = _banners[idx] as Map<String, dynamic>;
        return Stack(
          fit: StackFit.expand,
          children: [
            Container(
              decoration: const BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10)),
              ),
              clipBehavior: Clip.antiAlias,
              margin: const EdgeInsets.symmetric(vertical: 10),
              child: Tools.image(
                Tools.fixImageUrl(item['image']),
                width: bannerWidth,
                height: bannerHeight,
              ),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              heightFactor: 2,
              child: Padding(
                padding: const EdgeInsets.only(bottom: 25.0),
                child: Text(
                  item['title'],
                  style: const TextStyle(color: Colors.white),
                ),
              ),
            ),
          ],
        );
      },
      itemCount: _banners.length,
      controller: SwiperController(),
      pagination: const SwiperPagination(),
    );
  }
}

class _CategoryWidget extends StatelessWidget {
  final List<dynamic> _cates;
  final ScrollController _controller = ScrollController();

  _CategoryWidget(this._cates, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final width = (MediaQuery.of(context).size.width - 50) / 4;
    final colorScheme = Theme.of(context).colorScheme;
    return CardWidget(
      color: colorScheme.surface,
      margin: const EdgeInsets.only(left: 15, right: 15, bottom: 10),
      child: Scrollbar(
        thumbVisibility: true,
        controller: _controller,
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          controller: _controller,
          child: Padding(
            padding: const EdgeInsets.only(bottom: 15.0),
            child: ConstrainedBox(
              constraints:
                  BoxConstraints(maxWidth: (_cates.length + 1) ~/ 2 * width),
              child: Wrap(
                children: _cates
                    .map(
                      (item) => _CategoryItemWidget(
                        item,
                        itemWidth: width,
                      ),
                    )
                    .toList(),
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class _CategoryItemWidget extends StatelessWidget {
  final Map<String, dynamic> _item;
  final double itemWidth;

  const _CategoryItemWidget(this._item, {Key? key, this.itemWidth = 100})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    final icon = Tools.fixImageUrl(_item['icon']);
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(
          context,
          '/product/list',
          arguments: {"category": _item['id']},
        );
      },
      child: SizedBox(
        //height: 80,
        width: itemWidth,
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
              child: ClipOval(
                child: AspectRatio(
                  aspectRatio: 1,
                  child: Tools.image(icon),
                ),
              ),
            ),
            Text(
              _item['title'],
              overflow: TextOverflow.ellipsis,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.bold,
                decoration: TextDecoration.none,
              ),
              maxLines: 2,
            ),
          ],
        ),
      ),
    );
  }
}
